<template>
  <div class="playback-view">
    <card>
      <div class="playback-content flex-1 flex">
        <!-- 左侧文件夹树 -->
        <div class="left-panel w-80 flex-shrink-0 border-r border-gray-200 pr-4 flex flex-col">
          <!-- 控制面板 -->
          <PlaybackControlPanel 
            :selected-cameras="selectedCameras" 
            :selected-date="selectedDate"
            :is-loading="isLoadingPlayback"
            @sync-playback="handleSyncPlayback" 
            @async-playback="handleAsyncPlayback"
            @download-selected="handleDownloadSelected" 
            @search-devices="handleSearchDevices"
            @date-change="handleDateChange" 
          />

          <!-- 文件夹树和摄像头列表 -->
          <CameraTreeView :data="treeData" :default-expand-all="false" :show-header="false" :use-store-data="false"
            :enable-drag="false" :show-checkboxes="true" :show-drag-tip="false"
            :selected-cameras="selectedCameras.map(id => String(id))" :default-expanded-keys="defaultExpandedKeys"
            @node-click="handleNodeClick" @node-expand="handleNodeExpand" @control-ptz="handleControlPTZ"
            @refresh="handleRefreshTree" @camera-checkbox-change="handleCameraCheckboxChange" />
        </div>

        <!-- 右侧内容区域 -->
        <div class="right-panel flex-1 pl-4 flex flex-col">
          <!-- 全局加载状态指示器 -->
          <div v-if="isLoadingPlayback" class="loading-overlay fixed inset-0 z-50 bg-black bg-opacity-50 flex items-center justify-center">
            <div class="loading-content bg-white rounded-lg p-6 flex flex-col items-center gap-4">
              <el-icon class="text-4xl text-blue-500 animate-spin">
                <Loading />
              </el-icon>
              <div class="text-lg font-medium text-gray-700">正在加载回放数据...</div>
              <div class="text-sm text-gray-500">请稍候，正在获取流地址</div>
            </div>
          </div>
          
          <!-- 视频播放区域 -->
          <div v-if="hasStartedPlayback" class="video-playback-area flex-1 flex flex-col">
            
            <!-- 播放状态指示器 -->
            <div v-if="!isPlaying && !isLoadingPlayback" class="playback-status-overlay absolute top-4 left-1/2 transform -translate-x-1/2 z-20 bg-black bg-opacity-75 text-white px-4 py-2 rounded-lg">
              <div class="flex items-center gap-2">
                <el-icon class="text-yellow-400">
                  <VideoPause />
                </el-icon>
                <span>视频已暂停</span>
              </div>
            </div>
            
            <!-- 4分屏视频显示区域 -->
            <div class="video-grid gap-2 flex-1" :class="{
              'grid grid-cols-1': playingCameras.length === 1,
              'grid grid-cols-2': playingCameras.length >= 2,
            }">
              <!-- 视频显示区域 -->
              <div v-for="camera in playingCameras.slice(0, 4)" :key="camera.id"
                class="video-cntaioner border border-gray-300 rounded-lg overflow-hidden bg-black relative flex-1 min-h-0"
                :class="{
                  'cursor-pointer transition-all duration-200': playbackMode === 'async',
                  'ring-2 ring-blue-500': playbackMode === 'async' && selectedCameraForAsync?.id === camera.id
                }"
                @click="playbackMode === 'async' ? selectCameraForAsync(camera) : null">
                <!-- 摄像头信息覆盖层 -->
                <div class="camera-info-overlay absolute top-2 left-2 z-10 text-white">
                  <div class="camera-name text-sm font-medium">{{ camera.name }}</div>
                  <div class="camera-ip text-xs opacity-75">{{ camera.ip }}</div>
                  <div class="playback-time text-xs opacity-75 mt-1">{{ formatTime(currentPlaybackTime) }}</div>
                </div>

                <!-- 流地址状态信息 -->
                <div class="stream-status-overlay absolute top-2 right-2 z-10 text-white">
                  <div v-if="playbackStore.getCameraStreamUrl(camera.id.toString(), selectedDate, selectedTime)"
                    class="stream-status">
                    <div class="text-xs text-green-400">● 流地址已获取</div>
                  </div>
                  <div v-else-if="playbackStore.isLoadingStream" class="stream-status">
                    <div class="text-xs text-yellow-400">● 正在获取流地址...</div>
                  </div>
                  <div v-else-if="playbackStore.streamError" class="stream-status">
                    <div class="text-xs text-red-400">● 获取流地址失败</div>
                  </div>
                </div>

                <!-- VideoPlayer 组件 -->
                <div class="w-full h-full flex-1 min-h-0">
                  <VideoPlayer :video-url="getVideoUrl(camera)" :autoplay="true" :muted="true" :controls="false"
                    :show-custom-controls="false" ref="videoPlayerRefs" />
                </div>

              </div>
            </div>
            <VideoTimeline
              :style="{ height: '20%' }"
              ref="videoTimelineRef" :selected-date="selectedDate" :zoom-index="2" :window-data="windowList"
              :initial-time="''" :smooth-zoom="false" 
              :selected-cameras="playbackMode === 'async' && selectedCameraForAsync ? [selectedCameraForAsync.id.toString()] : selectedCameras"
              :selected-camera-for-async="selectedCameraForAsync"
              :playback-mode="playbackMode"
              @time-change="handleTimeChange" />
          </div>
          <!-- 默认提示区域 -->
          <div v-else class="content-placeholder flex items-center justify-center h-full text-gray-500">
            <div class="text-center">
              <el-icon class="text-6xl mb-4">
                <VideoCamera />
              </el-icon>
              <p>请从左侧选择摄像头查看录像</p>
            </div>
          </div>
        </div>
      </div>
    </card>

    <!-- 录像记录列表弹框 -->
    <RecordListDialog :visible="recordListDialogVisible" :camera="playbackStore.selectedCamera"
      @update:visible="recordListDialogVisible = $event" @play="handlePlayRecord" @download="handleDownloadRecord" />

    <!-- 录像播放器弹框 -->
    <PlaybackDialog :visible="playbackDialogVisible" :record="playbackStore.selectedRecord"
      :is-playing="playbackStore.isPlaying" :playback-position="playbackStore.playbackPosition"
      @update:visible="playbackDialogVisible = $event" @update:is-playing="playbackStore.isPlaying = $event"
      @update:playback-position="playbackStore.playbackPosition = $event" @seek="handleSeek" @download="handleDownload"
      @close="handleCloseDialog" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, nextTick } from 'vue'
import {
  ElIcon
} from 'element-plus'
import { success, error, warning, info } from '@/utils/toast'
import { confirm } from '@/utils/confirm'
import {
  VideoCamera,
  VideoPause,
  Loading
} from '@element-plus/icons-vue'
import card from '@/components/card/index.vue'
import PlaybackControlPanel from '@/components/PlaybackControlPanel.vue'
import CameraTreeView from '@/components/CameraTreeView.vue'
import PlaybackDialog from '@/components/PlaybackDialog.vue'
import RecordListDialog from '@/components/RecordListDialog.vue'
import { usePlaybackStore } from '@/stores/playback'
import type { PlaybackRecord } from '@/stores/playback'
import type { Device, PlaybackQueryParams } from '@/types'
import { $getDeviceListByKeyword } from '@/api/device'
import { batchQueryVodRecords, setPlaybackStreamServers } from '@/api/playback'
import VideoTimeline from '@/components/VideoPlaybackControl.vue'
import VideoPlayer from '@/components/VideoPlayer.vue'

// 使用store
const playbackStore = usePlaybackStore()

// 弹框状态
const playbackDialogVisible = ref(false)
const recordListDialogVisible = ref(false)

// 当前录像记录
const currentRecordList = ref<PlaybackRecord[]>([])

// 控制面板数据
const selectedCameras = ref<string[]>([])
const searchResults = ref<Device[]>([])
const isSearching = ref(false)
const defaultExpandedKeys = ref<string[]>([])

// 播放相关数据 - 使用playback store中的isPlaying状态
const isPlaying = computed(() => playbackStore.isPlaying)
const playingCameras = ref<Device[]>([])
const currentPlaybackTime = ref(0) // 当前播放时间（秒）
const totalPlaybackTime = ref(0) // 总播放时间（秒）
const playbackMode = ref<'sync' | 'async' | null>(null) // 播放模式
const hasStartedPlayback = ref(false) // 是否已开始播放（用于区分未开始和暂停状态）
const isLoadingPlayback = ref(false) // 是否正在加载回放数据
const selectedCameraForAsync = ref<Device | null>(null) // 异步回放时选中的摄像头

// 存储每个摄像头的当前流地址，避免时间变化时丢失
const cameraStreamUrls = ref<Map<string, string>>(new Map())

// 日期选择相关
const selectedDate = ref(new Date().toISOString().slice(0, 10)) // 默认使用今天的日期
const selectedTime = ref('00:00:00') // 默认时间

// VideoTimeline组件引用
const videoTimelineRef = ref()

// VideoPlayer组件引用数组
const videoPlayerRefs = ref<any[]>([])

// 时间轴相关数据
const timeSegments = ref<any[]>([]) // 时间段数据
const windowList = ref<any[]>([]) // 窗口时间段数据



// 将TreeNode转换为CameraTreeView需要的格式
const convertTreeNodeToCameraTreeNode = (node: any): any => {
  const cameraNode = {
    id: String(node.id),
    name: node.name,
    type: 'folder',
    parentId: String(node.parentId),
    children: node.children?.map(convertTreeNodeToCameraTreeNode) || []
  }

  // 如果有设备，将设备转换为摄像头节点
  const cameras = playbackStore.folderCameraMap.get(parseInt(node.id))
  console.log('Converting node:', node.name, 'id:', node.id, 'cameras:', cameras)
  if (cameras && cameras.length > 0) {
    const deviceNodes = cameras.map(device => ({
      id: `device_${device.id}`,
      name: device.name,
      type: 'camera' as const,
      status: device.status === 1 ? 'online' : 'offline',
      ip: device.ip,
      url: device.flv || device.flvsub,
      parentId: String(node.id),
      hasMapMarker: false,
      nvrId: device.nvrId,
      subEquId: device.subEquId,
      ptzEnable: device.ptzEnable
    }))

    // 将设备节点添加到子节点中
    if (cameraNode.children) {
      cameraNode.children.push(...deviceNodes)
    } else {
      cameraNode.children = deviceNodes
    }
  }

  return cameraNode
}

// 生成包含摄像头子节点的树形数据
const treeData = computed(() => {
  // 如果有搜索结果，显示搜索结果
  if (searchResults.value.length > 0) {
    const searchNode = {
      id: 'search_results',
      name: `搜索结果 (${searchResults.value.length})`,
      type: 'folder',
      parentId: null,
      children: searchResults.value.map(device => ({
        id: `device_${device.id}`,
        name: device.name,
        type: 'camera' as const,
        status: device.status === 1 ? 'online' : 'offline',
        ip: device.ip,
        url: device.flv || device.flvsub,
        parentId: 'search_results',
        hasMapMarker: false,
        nvrId: device.nvrId,
        subEquId: device.subEquId,
        ptzEnable: device.ptzEnable
      }))
    }
    return [searchNode]
  }

  // 正常显示树形数据
  console.log('Computing treeData, folderCameraMap:', playbackStore.folderCameraMap)
  const result = playbackStore.menuTree.map(convertTreeNodeToCameraTreeNode)
  console.log('Computed treeData:', result)
  return result
})



// 方法
const handleNodeClick = async (node: any) => {
  console.log('Node clicked:', node)

  // 如果是摄像头节点，处理摄像头选择
  if (node.type === 'camera') {
    const deviceId = parseInt(node.id.replace('device_', ''))

    // 如果是搜索结果中的设备
    if (node.parentId === 'search_results') {
      const camera = searchResults.value.find(c => c.id === deviceId)
      if (camera) {
        await handleSelectCamera(camera)
      }
      return
    }

    // 正常树形结构中的设备
    const camera = playbackStore.folderCameraMap.get(parseInt(node.parentId))?.find(c => c.id === deviceId)
    if (camera) {
      await handleSelectCamera(camera)
    }
    return
  }

  // 如果是文件夹节点，按需加载摄像头
  if (node.type === 'folder') {
    const folderId = parseInt(node.id)

    // 如果该文件夹的摄像头还没有加载，则加载
    if (!playbackStore.folderCameraMap.has(folderId)) {
      console.log('Loading cameras for clicked folder:', folderId)
      const cameras = await playbackStore.loadCameraList(folderId, 1, 20)
      console.log('Loaded cameras for folder', folderId, ':', cameras)
      // 将摄像头列表存储到对应的文件夹中
      playbackStore.folderCameraMap.set(folderId, cameras)
      console.log('folderCameraMap after setting:', playbackStore.folderCameraMap)
    }

    // 更新选中的节点
    playbackStore.handleNodeClick({ id: folderId, name: node.name, parentId: node.parentId })

    // 清空录像记录
    currentRecordList.value = []
  }
}

const handleNodeExpand = async (node: any) => {
  console.log('Node expanded:', node)

  // 如果是文件夹节点，按需加载摄像头
  if (node.type === 'folder') {
    const folderId = parseInt(node.id)

    // 如果该文件夹的摄像头还没有加载，则加载
    if (!playbackStore.folderCameraMap.has(folderId)) {
      console.log('Loading cameras for expanded folder:', folderId)
      const cameras = await playbackStore.loadCameraList(folderId, 1, 20)
      console.log('Loaded cameras for folder', folderId, ':', cameras)
      // 将摄像头列表存储到对应的文件夹中
      playbackStore.folderCameraMap.set(folderId, cameras)
      console.log('folderCameraMap after setting:', playbackStore.folderCameraMap)
    }
  }
}

const handleControlPTZ = (camera: any) => {
  // 录像回放页面不需要云台控制，但需要保持接口兼容
  console.log('PTZ control requested for:', camera.name)
}

const handleRefreshTree = () => {
  // 刷新树形数据
  playbackStore.folderCameraMap.clear()
  playbackStore.initializeData()
  success('目录树已刷新')
}

// 处理摄像机复选框变化
const handleCameraCheckboxChange = (camera: any, checked: boolean) => {
  if (checked) {
    // 添加到选中列表，确保ID是字符串类型
    const cameraId = camera.id.toString()
    if (!selectedCameras.value.includes(cameraId)) {
      selectedCameras.value.push(cameraId)
    }
  } else {
    // 从选中列表移除
    const cameraId = camera.id.toString()
    const index = selectedCameras.value.indexOf(cameraId)
    if (index > -1) {
      selectedCameras.value.splice(index, 1)
    }
  }
}

const handleSelectCamera = async (camera: Device) => {
  playbackStore.selectCamera(camera)
  // 打开录像记录弹框
  recordListDialogVisible.value = true
}

// 控制面板方法
const handleSyncPlayback = async (selectedCameras: string[]) => {
  if (selectedCameras.length === 0) {
    error('同步回放路数2-4路')
    return
  }
  if (selectedCameras.length >= 1 && selectedCameras.length < 2) {
    error('同步回放路数2-4路')
    return
  }
  if (selectedCameras.length > 4) {
    error('同步回放路数2-4路')
    return
  }

  // 获取选中的摄像头设备信息
  const cameras = getSelectedCameras(selectedCameras)
  if (cameras.length === 0) {
    error('未找到选中的摄像头')
    return
  }

  // 确保有选择的日期
  if (!selectedDate.value) {
    selectedDate.value = new Date().toISOString().slice(0, 10) // YYYY-MM-DD格式
  }

  try {
    // 开始加载
    isLoadingPlayback.value = true
    
    // 查询录像记录
    await queryPlaybackRecords(cameras)

    // 生成回放流地址
    console.log('开始生成回放流地址...')
    await playbackStore.generateBatchPlaybackStreamUrls(cameras, selectedDate.value, selectedTime.value)
    console.log('回放流地址生成完成')

    // 缓存流地址到本地
    cameras.forEach(camera => {
      const cameraId = camera.id.toString()
      const streamUrl = playbackStore.getCameraStreamUrl(cameraId, selectedDate.value, selectedTime.value)
      if (streamUrl) {
        cameraStreamUrls.value.set(cameraId, streamUrl)
        console.log(`缓存摄像头 ${camera.name} 的流地址:`, streamUrl)
      }
    })

    // 设置播放模式和数据
    playbackMode.value = 'sync'
    playingCameras.value = cameras
    hasStartedPlayback.value = true
    playbackStore.isPlaying = true

    // 初始化播放时间（这里可以根据实际需求设置）
    totalPlaybackTime.value = 24 * 60 * 60 // 24小时的总时长（秒）
    // 不重置currentPlaybackTime，让TimeLine组件使用选择的日期作为初始时间

    // 生成时间段数据
    generateTimeSegments()
    generateWindowList()

    // 强制重新渲染TimeLine组件
    nextTick(() => {
      if (videoTimelineRef.value && videoTimelineRef.value.forceRerender) {
        videoTimelineRef.value.forceRerender()
        console.log('父组件 - 强制重新渲染TimeLine组件')
      }
    })

    success(`开始同步回放 ${cameras.length} 路视频`)
  } catch (err) {
    console.error('同步回放失败:', err)
    error(`同步回放失败: ${err instanceof Error ? err.message : '请重试'}`)
  } finally {
    // 结束加载
    isLoadingPlayback.value = false
  }
}

const handleAsyncPlayback = async (selectedCameras: string[]) => {
  if (selectedCameras.length === 0) {
    error('异步回放路数1-4路')
    return
  }
  if (selectedCameras.length > 4) {
    error('异步回放路数1-4路')
    return
  }

  // 获取选中的摄像头设备信息
  const cameras = getSelectedCameras(selectedCameras)
  if (cameras.length === 0) {
    error('未找到选中的摄像头')
    return
  }

  // 确保有选择的日期
  if (!selectedDate.value) {
    selectedDate.value = new Date().toISOString().slice(0, 10) // YYYY-MM-DD格式
  }

  try {
    // 开始加载
    isLoadingPlayback.value = true
    
    // 查询录像记录
    await queryPlaybackRecords(cameras)

    // 生成回放流地址
    console.log('开始生成回放流地址...')
    await playbackStore.generateBatchPlaybackStreamUrls(cameras, selectedDate.value, selectedTime.value)
    console.log('回放流地址生成完成')

    // 缓存流地址到本地
    cameras.forEach(camera => {
      const cameraId = camera.id.toString()
      const streamUrl = playbackStore.getCameraStreamUrl(cameraId, selectedDate.value, selectedTime.value)
      if (streamUrl) {
        cameraStreamUrls.value.set(cameraId, streamUrl)
        console.log(`缓存摄像头 ${camera.name} 的流地址:`, streamUrl)
      }
    })

    // 设置播放模式和数据
    playbackMode.value = 'async'
    playingCameras.value = cameras
    selectedCameraForAsync.value = cameras[0] // 异步回放默认选中第一个摄像头
    hasStartedPlayback.value = true
    playbackStore.isPlaying = true

    // 初始化播放时间（这里可以根据实际需求设置）
    totalPlaybackTime.value = 24 * 60 * 60 // 24小时的总时长（秒）
    // 不重置currentPlaybackTime，让TimeLine组件使用选择的日期作为初始时间

    // 生成时间段数据
    generateTimeSegments()
    generateWindowList()

    // 强制重新渲染TimeLine组件
    nextTick(() => {
      if (videoTimelineRef.value && videoTimelineRef.value.forceRerender) {
        videoTimelineRef.value.forceRerender()
        console.log('父组件 - 强制重新渲染TimeLine组件')
      }
    })

    success(`开始异步回放 ${cameras.length} 路视频`)
  } catch (err) {
    console.error('异步回放失败:', err)
    error(`异步回放失败: ${err instanceof Error ? err.message : '请重试'}`)
  } finally {
    // 结束加载
    isLoadingPlayback.value = false
  }
}

const handleDownloadSelected = (selectedCameras: string[]) => {
  if (selectedCameras.length === 0) {
    warning('请先选择要下载的摄像头')
    return
  }
  info(`开始下载 ${selectedCameras.length} 个摄像头的录像`)
}

// 获取选中的摄像头设备信息
const getSelectedCameras = (cameraIds: string[]): Device[] => {
  const cameras: Device[] = []

  // 从所有文件夹的摄像头中查找选中的摄像头
  for (const [, folderCameras] of playbackStore.folderCameraMap) {
    for (const camera of folderCameras) {
      const deviceId = `device_${camera.id}`
      if (cameraIds.includes(deviceId)) {
        cameras.push(camera)
      }
    }
  }

  // 从搜索结果中查找选中的摄像头
  for (const camera of searchResults.value) {
    const deviceId = `device_${camera.id}`
    if (cameraIds.includes(deviceId)) {
      cameras.push(camera)
    }
  }

  return cameras
}

// 查询录像记录
const queryPlaybackRecords = async (cameras: Device[]) => {
  if (!selectedDate.value) {
    throw new Error('请选择查询日期')
  }

  try {
    // 构建查询参数
    const queries: PlaybackQueryParams[] = cameras.map(camera => ({
      EquId: camera.equId, // 使用摄像头的实际equId
      nvrId: camera.nvrId,
      ChannelId: camera.subEquId,
      StartTime: `${selectedDate.value}T00:00:00`,
      EndTime: `${selectedDate.value}T23:59:59`
    }))

    console.log('录像查询参数:', queries)
    console.log('选择的摄像头:', cameras)

    // 批量查询录像记录
    const response = await batchQueryVodRecords(queries)

    if (response.success && response.data && response.data.length > 0) {
      const allRecords = response.data[0].records
      console.log('查询到录像记录:', allRecords)

      // 将查询结果存储到store中，供时间轴组件使用
      playbackStore.setPlaybackRecords(allRecords)

      return allRecords
    } else {
      console.log('未查询到录像记录')
      playbackStore.setPlaybackRecords([])
      return []
    }
  } catch (error) {
    console.error('查询录像记录失败:', error)
    throw error
  }
}




// 生成时间段数据
const generateTimeSegments = () => {
  const segments = []
  const colors = ['#4CAF50', '#2196F3', '#FF9800', '#E91E63', '#9C27B0', '#00BCD4']

  // 使用选择的日期或今天
  let targetDate: Date
  if (selectedDate.value) {
    targetDate = new Date(selectedDate.value)
  } else {
    targetDate = new Date()
  }

  const startOfDay = new Date(targetDate.getFullYear(), targetDate.getMonth(), targetDate.getDate()).getTime()

  // 使用真实的录像数据
  if (playbackStore.playbackRecords.length > 0) {
    console.log('使用真实录像数据生成时间段:', playbackStore.playbackRecords)

    // 按设备分组录像记录
    const recordsByCamera = new Map<number, any[]>()

    playbackStore.playbackRecords.forEach(record => {
      const cameraId = record.equId || 0
      if (!recordsByCamera.has(cameraId)) {
        recordsByCamera.set(cameraId, [])
      }
      recordsByCamera.get(cameraId)!.push(record)
    })

    // 为每个设备的录像记录生成时间段
    let colorIndex = 0
    recordsByCamera.forEach((records, cameraId) => {
      records.forEach((record, index) => {
        const startTime = new Date(record.startTime).getTime()
        const endTime = new Date(record.endTime).getTime()

        segments.push({
          beginTime: startTime,
          endTime: endTime,
          color: colors[colorIndex % colors.length],
          startRatio: 0.1 + (cameraId * 0.1), // 不同设备在不同高度
          endRatio: 0.1 + (cameraId * 0.1) + 0.05,
          label: `设备${cameraId}-录制${index + 1}`,
          cameraId: cameraId,
          recordIndex: record.index
        })
      })
      colorIndex++
    })
  } else {
    // 如果没有录像数据，生成随机时间段作为占位符
    console.log('没有录像数据，生成随机时间段')
    const segmentCount = Math.floor(Math.random() * 3) + 3
    for (let i = 0; i < segmentCount; i++) {
      const startHour = Math.floor(Math.random() * 20) + 2 // 2-21点
      const duration = Math.floor(Math.random() * 4) + 1 // 1-4小时

      segments.push({
        beginTime: startOfDay + startHour * 60 * 60 * 1000,
        endTime: startOfDay + (startHour + duration) * 60 * 60 * 1000,
        color: colors[i % colors.length],
        startRatio: 0.6,
        endRatio: 0.9,
        label: `录制${i + 1}`
      })
    }
  }

  timeSegments.value = segments
  console.log('生成的时间段数据:', segments)
}

// 生成窗口时间段数据
const generateWindowList = () => {
  const windows: any[] = []

  playingCameras.value.forEach((camera, index) => {
    const cameraSegments: any[] = []
    const colors = ['#E91E63', '#9C27B0', '#00BCD4', '#4CAF50']

    // 使用选择的日期或今天
    let targetDate: Date
    if (selectedDate.value) {
      targetDate = new Date(selectedDate.value)
    } else {
      targetDate = new Date()
    }

    const startOfDay = new Date(targetDate.getFullYear(), targetDate.getMonth(), targetDate.getDate()).getTime()

    // 为每个摄像头生成1-2个时间段（在当天内）
    const segmentCount = Math.floor(Math.random() * 2) + 1
    for (let i = 0; i < segmentCount; i++) {
      const startHour = Math.floor(Math.random() * 18) + 3 // 3-20点
      const duration = Math.floor(Math.random() * 3) + 1 // 1-3小时

      cameraSegments.push({
        beginTime: startOfDay + startHour * 60 * 60 * 1000,
        endTime: startOfDay + (startHour + duration) * 60 * 60 * 1000,
        color: colors[index % colors.length],
        startRatio: 0.6,
        endRatio: 0.9
      })
    }

    windows.push({
      label: camera.name,
      status: camera.status === 1 ? '在线' : '离线',
      timeSegments: cameraSegments
    })
  })

  windowList.value = windows
}


// 格式化时间显示
const formatTime = (seconds: number): string => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 获取摄像头的视频URL，优先使用缓存的流地址
const getVideoUrl = (camera: Device): string => {
  const cameraId = camera.id.toString()

  // 首先尝试从缓存中获取
  if (cameraStreamUrls.value.has(cameraId)) {
    return cameraStreamUrls.value.get(cameraId)!
  }

  // 如果缓存中没有，尝试从store获取
  const storeUrl = playbackStore.getCameraStreamUrl(cameraId, selectedDate.value, selectedTime.value)
  if (storeUrl) {
    // 缓存这个URL
    cameraStreamUrls.value.set(cameraId, storeUrl)
    return storeUrl
  }

  // 如果都没有，返回空字符串
  return ''
}

// 处理时间轴时间变化
const handleTimeChange = async (timestamp: number) => {
  console.log('时间轴时间变化:', new Date(timestamp))

  // 更新时间显示
  const date = new Date(timestamp)
  const timeString = `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`
  selectedTime.value = timeString

  // 如果正在播放，通知所有视频播放器进行 seek 操作
  if (isPlaying.value && playingCameras.value.length > 0) {
    try {
      console.log('时间变化，执行 seek 操作...')

      // 通知所有视频播放器进行 seek 操作，避免显示"暂无视频"
      nextTick(() => {
        videoPlayerRefs.value.forEach((playerRef, index) => {
          if (playerRef && playerRef.handleSeek) {
            console.log(`第${index + 1}个视频播放器执行 seek 操作`)
            playerRef.handleSeek()
          }
        })
      })
    } catch (error) {
      console.error('执行 seek 操作失败:', error)
    }
  }
}

// 设置选择的日期
const setSelectedDate = (date: string) => {
  selectedDate.value = date
  console.log('选择的日期:', date)

  // 重新生成时间段数据
  generateTimeSegments()
  generateWindowList()

  // 如果正在播放，重新生成时间段数据
  if (isPlaying.value) {
    generateTimeSegments()
    generateWindowList()
  }
}

// 处理日期变化事件
const handleDateChange = (date: string) => {
  console.log('父组件收到日期变化:', date)
  setSelectedDate(date)

  // 清除流地址缓存
  playbackStore.clearStreamUrls()

  // 停止所有视频播放
  stopAllVideoPlayers()
}

// 停止所有视频播放器
const stopAllVideoPlayers = () => {
  videoPlayerRefs.value.forEach((playerRef, index) => {
    if (playerRef && playerRef.stopPlay) {
      console.log(`停止第${index + 1}个视频播放器`)
      playerRef.stopPlay()
    }
  })

  // 清除流地址缓存
  cameraStreamUrls.value.clear()
  console.log('清除流地址缓存')
}

// 导出方法供外部使用
defineExpose({
  setSelectedDate
})


// 搜索设备处理方法
const handleSearchDevices = async (keyword: string) => {
  if (!keyword.trim()) {
    // 清空搜索，恢复原始树形数据
    searchResults.value = []
    isSearching.value = false
    defaultExpandedKeys.value = []
    return
  }

  try {
    isSearching.value = true
    const response = await $getDeviceListByKeyword(keyword.trim())

    if (response.data && Array.isArray(response.data)) {
      searchResults.value = response.data
      isSearching.value = false
      // 自动展开搜索结果文件夹
      defaultExpandedKeys.value = ['search_results']
      info(`找到 ${response.data.length} 个匹配的设备`)
    } else {
      searchResults.value = []
      isSearching.value = false
      defaultExpandedKeys.value = []
      info('未找到匹配的设备')
    }
  } catch (error) {
    console.error('搜索设备失败:', error)
    searchResults.value = []
    isSearching.value = false
    defaultExpandedKeys.value = []
    info('搜索设备失败，请重试')
  }
}





const handleDownload = async (record: PlaybackRecord) => {
  try {
    await confirm.delete(record.cameraName, '录像')
    await playbackStore.downloadRecord(record)
    success(`开始下载: ${record.cameraName} - ${record.startTime}`)
  } catch (error) {
    // 用户取消下载
  }
}

const handleSeek = (position: number) => {
  playbackStore.seekToPosition(position)
}

const handleCloseDialog = () => {
  playbackDialogVisible.value = false
  playbackStore.isPlaying = false
  playbackStore.playbackPosition = 0
  hasStartedPlayback.value = false
  selectedCameraForAsync.value = null
}

// 异步回放时选择摄像头
const selectCameraForAsync = (camera: Device) => {
  if (playbackMode.value === 'async') {
    selectedCameraForAsync.value = camera
    console.log('切换到摄像头:', camera.name)
  }
}


// 播放录像记录
const handlePlayRecord = (record: PlaybackRecord) => {
  playbackStore.selectedRecord = record
  playbackDialogVisible.value = true
  recordListDialogVisible.value = false
  info(`打开播放器: ${record.cameraName}`)
}

// 下载录像记录
const handleDownloadRecord = async (record: PlaybackRecord) => {
  try {
    await confirm.delete(record.cameraName, '录像')
    await playbackStore.downloadRecord(record)
    success(`开始下载: ${record.cameraName} - ${record.startTime}`)
  } catch (error) {
    // 用户取消下载
  }
}
// 生命周期
onMounted(async () => {
  await playbackStore.initializeData()

  // 设置录像查询的流媒体服务器信息
  if (playbackStore.streamServer.length > 0 && playbackStore.streamPort) {
    setPlaybackStreamServers(playbackStore.streamServer, playbackStore.streamPort)
    console.log('录像查询服务器信息已设置:', {
      servers: playbackStore.streamServer,
      port: playbackStore.streamPort
    })
  } else {
    console.warn('流媒体服务器信息未获取到:', {
      streamServerLength: playbackStore.streamServer.length,
      streamPort: playbackStore.streamPort
    })
  }
})
</script>

<style scoped lang="scss">
.playback-view {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.playback-content {
  min-height: 0;
}

// 左侧面板样式已移至CameraTreeView组件中

.right-panel {
  .content-placeholder {
    .el-icon {
      color: #9ca3af;
    }
  }

  .video-playback-area {
    .video-grid {
      .video-container {
        // position: relative;
        .camera-info-overlay {
          background: rgba(0, 0, 0, 0.6);
          padding: 8px 12px;
          border-radius: 4px;
          backdrop-filter: blur(4px);

          .camera-name {
            font-weight: 600;
            margin-bottom: 2px;
          }

          .camera-ip {
            color: #d1d5db;
          }

          .playback-time {
            color: #9ca3af;
          }
        }

        .stream-status-overlay {
          background: rgba(0, 0, 0, 0.6);
          padding: 4px 8px;
          border-radius: 4px;
          backdrop-filter: blur(4px);

          .stream-status {
            text-align: right;
          }
        }
      }
    }
  }
}

// 树形相关样式已移至CameraTreeView组件中

// 选中行样式
:deep(.selected-row) {
  background-color: #e6f7ff !important;
}

.loading-container {
  background-color: #f9fafb;
  border-radius: 8px;
}
</style>